/**
 * Copyright (C) 2011 KingCore Science & Technology CO,.LTD. All rights reserved.
 * XNS PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

/**
 * Copyright (C) 2002-2011 WUZEWEN. All rights reserved.
 * WUZEWEN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 * This software is the confidential and proprietary information of
 * WuZeven, Personal. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with WuZeven.
 */

package com.kingcore.director.core.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Observable;
import java.util.Observer;
import java.util.ResourceBundle;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToggleButton;

import wzw.util.I18nUtil;
import wzw.util.I18nUtils;

import com.kingcore.director.DirectorConstants;
import com.kingcore.director.core.util.DirectorComponentUtils;

/**
 * <p>java类文件的说明...</p>
 * @author Zeven/wzw on Jul 17, 2011
 * @version	1.0
 * @see		Object#equals(java.lang.Object)
 * @since	JDK5
 */

public class CommonSearchPanel extends JPanel implements MouseListener, KeyListener, ActionListener, Observer {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private CommonSearchable parent = null;
	private JTable table = null;
	public CommonSearchPanel( CommonSearchable parent, JTable obj) {
		super();
		this.parent = parent;
		this.table = obj;
		initializeInterface();
	}
	
	JLabel lbl_search = null;
	private void initializeInterface(){


		this.add(getCloseSearch(), null);
		this.add(getKeywordTextField(), null);
		
		//当前界面查找用Find，后台更多搜索用Search
		this.setLayout(null);
		lbl_search = new JLabel("Find:");
		lbl_search.setBounds(new java.awt.Rectangle(25,3,50,23));
		this.add(lbl_search, null);

		this.add(getNextMatched(), null);
		this.add(getPriorMatched(), null);
		this.add(getHighLightAll(), null);
		this.add(getCaseSensitive(), null);
		
		this.getKeywordTextField().requestFocusInWindow();
		
		this.update(null,null);
	}
	
	/**
	 * <p>java方法的说明...</p>
	 * @author Zeven on Jul 17, 2011
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	private JButton closeSearch  = null;
	private JButton getCloseSearch(){
		if (closeSearch==null) {
			closeSearch = new JButton();
			closeSearch.setBounds(new java.awt.Rectangle(5,7,15,15));
			closeSearch.setIcon( new ImageIcon("./resource/closeSearch.gif"));
			closeSearch.addMouseListener(this);
		}
		return closeSearch;
	}
 

	private JTextField keywordTextField = null;
	public JTextField getKeywordTextField(){
		if (keywordTextField==null) {
			keywordTextField = new JTextField();
			keywordTextField.setToolTipText("Search word input(Ctrl+F),输入后回车");
			keywordTextField.setBounds(new java.awt.Rectangle(53,2,150,25));
			keywordTextField.addKeyListener(this);
		}
		return keywordTextField;
	}

	private JButton nextMatched  = null;
	private JButton getNextMatched(){
		if (nextMatched==null) {
			nextMatched = new JButton();
			nextMatched.setBounds(new java.awt.Rectangle(208,1,88,25));
			nextMatched.setText("Next one");
			nextMatched.addActionListener(this);
		}
		return nextMatched;
	}
	
	private JButton priorMatched  = null;
	private JButton getPriorMatched(){
		if (priorMatched==null) {
			priorMatched = new JButton();
			priorMatched.setBounds(new java.awt.Rectangle(297,1,91,25));
			priorMatched.setText("Prior one");
			priorMatched.addActionListener(this);
		}
		return priorMatched;
	}


	private JToggleButton highLightAll  = null;
	private JToggleButton getHighLightAll(){
		if (highLightAll==null) {
			highLightAll = new JToggleButton();
			highLightAll.setBounds(new java.awt.Rectangle(390,1,120,25));
			highLightAll.setText("Hightlight all");
			highLightAll.addActionListener(this);
		}
		return highLightAll;
	}

	private JCheckBox caseSensitive  = null;
	private JCheckBox getCaseSensitive(){
		if (caseSensitive==null) {
			caseSensitive = new JCheckBox();
			caseSensitive.setBounds(new java.awt.Rectangle(510,3,110,23));
			caseSensitive.setText("Case sensitive");
			caseSensitive.addActionListener(this);
		}
		return caseSensitive;
	}
	
	public void mouseClicked(MouseEvent e) {
		Object obj = e.getSource() ;
		if(obj== getCloseSearch()){
			this.parent.closeCommonSearchPanel(); //关闭面板
		}else if(obj == this.getNextMatched()){
			executeSearch();
			
		}
	}

	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void keyPressed(KeyEvent e) {
		int keyCode = e.getKeyCode();
		Object eventObj = e.getSource();
		if (keyCode == KeyEvent.VK_ENTER) {
			if (eventObj == this.getKeywordTextField()) {
				executeSearch();
			}
		}
		
	}

	private void doSearchNext(String direction) {
		String keyword =  this.getKeywordTextField().getText();
		if (keyword==null ||  keyword.trim().length()<1 ) {
			return ;
		}
		isFound = false;
		int rowCount = this.table.getRowCount();
		int colCount = this.table.getColumnCount();
		Object colVal = null;
		int beginPos ;
		if ("asc".equals(direction)) {
			beginPos = Math.max( this.currentRowNum+1, 0);
			beginPos = beginPos>=rowCount?0:beginPos;
		} else {
			beginPos = Math.min( this.currentRowNum-1, rowCount);
			beginPos = beginPos<0?rowCount-1:beginPos;
		}
		boolean isCaseSensitive = this.getCaseSensitive().isSelected();
		if (isCaseSensitive==false) {
			keyword = keyword.toLowerCase();
		}
		for (int i = beginPos; i>-1&&i<rowCount; ) {
			for (int j = 0; j < colCount; j++) {
				if(this.table.getColumnModel().getColumn(j).getWidth()<1)
					continue;  //如果列宽度小于1，则是隐藏列，不处理
				
				colVal = this.table.getValueAt(i, j);
				if (colVal==null) {
					continue;
				}
				if (isCaseSensitive==false) {
					colVal = colVal.toString().toLowerCase();
				}
				if ( colVal.toString().indexOf(keyword)>-1) {
					currentRowNum = i;
					this.table.setRowSelectionInterval(i, i);
					DirectorComponentUtils.scrollToRow(this.table, i);
					isFound = true;
					break;
				}
			}
			if (isFound ) {
				break;
			}
			if ("asc".equals(direction)) {
				i++;
			}else{
				i--;
			}
		}
		if (isFound == false) {
			this.currentRowNum = -1;
		}
	}
	
	private boolean isFound = false;
	private int currentRowNum = -1;
	/**
	 * 
	 * @return 查找到、高亮度行数
	 */
	public int executeSearch() {
		if (this.table.getRowCount()>0) {
			this.table.removeRowSelectionInterval(0, this.table.getRowCount()-1);
		}
		
		int findRowNum = -1;
		String keyword =  this.getKeywordTextField().getText();
		if (keyword==null ||  keyword.trim().length()<1 ) {
			return findRowNum;
		}
		isFound = false;
		currentRowNum= -1; // 重新初始 
		int rowCount = this.table.getRowCount();
		int colCount = this.table.getColumnCount();
		Object colVal = null;
		boolean isHighLigthAll = this.getHighLightAll().isSelected();
		boolean isCaseSensitive = this.getCaseSensitive().isSelected();
		if (isCaseSensitive==false) {
			keyword = keyword.toLowerCase();
		}
		for (int i = 0; i < rowCount; i++) {
			for (int j = 0; j < colCount; j++) {
				
				if(this.table.getColumnModel().getColumn(j).getWidth()<1)
					continue;  //如果列宽度小于1，则是隐藏列，不处理
				colVal = this.table.getValueAt(i, j);
				if (colVal==null) {
					continue;
				}
				if (isCaseSensitive==false) {
					colVal = colVal.toString().toLowerCase();
				}
				if ( colVal.toString().indexOf(keyword) >-1) {
					currentRowNum = i;
					if (currentRowNum>i) {
						continue;
					}
					isFound = true;
					if (isHighLigthAll) {
						this.table.addRowSelectionInterval(i, i);
						findRowNum ++;
					}else{
						this.table.setRowSelectionInterval(i, i);
						findRowNum ++;
					}
					DirectorComponentUtils.scrollToRow(this.table, i);  //滚动到该行
					break;
				}
			}
			if (isFound && isHighLigthAll==false) {
				break;
			}
		}
		return findRowNum;
	}

	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void actionPerformed(ActionEvent e) {
		Object eventObj = e.getSource();
		if (eventObj == this.getNextMatched()) {
			doSearchNext("asc");
			
		}else if (eventObj == this.getPriorMatched()) {
			doSearchNext("desc");
		}else if (eventObj==this.getHighLightAll()
				    || eventObj==getCaseSensitive() ) {
			executeSearch();
		}
	}

	@Override
	public void update(Observable o, Object arg) {
		ResourceBundle bundle = I18nUtils.getBundle(DirectorConstants.I18n_Language_Name);

		//I18nUtil.getBundleString(bundle, MainFrame.class, "tab.reminderMainPanel.Text")
		this.lbl_search.setText(I18nUtil.getBundleString(bundle, CommonSearchPanel.class, "lbl_search.Text"));
		this.nextMatched.setText(I18nUtil.getBundleString(bundle, CommonSearchPanel.class, "nextMatched.Text"));
		this.priorMatched.setText(I18nUtil.getBundleString(bundle, CommonSearchPanel.class, "priorMatched.Text"));
		this.highLightAll.setText(I18nUtil.getBundleString(bundle, CommonSearchPanel.class, "highLightAll.Text"));
		this.caseSensitive.setText(I18nUtil.getBundleString(bundle, CommonSearchPanel.class, "caseSensitive.Text"));
	}
 
}
